package com.dap.cms.governance.controller;

import com.dap.cms.governance.constant.ExcutorConstant;
import com.dap.cms.governance.exception.ServiceException;
import com.dap.cms.governance.po.CmsComponentManagerPo;
import com.dap.cms.governance.po.CmsManagerPo;
import com.dap.cms.governance.service.CmsComponentManagerService;
import com.dap.cms.governance.service.CmsManagerService;
import com.dap.cms.governance.util.BeanValidator;
import com.dap.cms.governance.vo.ManagerInfoVo;
import com.dap.dao.model.QueryResult;
import com.fesine.commons.entity.Result;
import com.fesine.commons.enums.ResultEnum;
import com.fesine.commons.util.CryptographyUtil;
import com.fesine.commons.util.ResultUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: t_cms_manager表对应的控制层类
 * @author: Fesine
 * @createTime:2018/08/20
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2018/08/20
 */
@RestController
@RequestMapping("/v1")
public class CmsManagerController {
    private static final Logger logger = LoggerFactory.getLogger(CmsManagerController.class);
    @Autowired
    private CmsManagerService cmsManagerService;
    @Autowired
    private CmsComponentManagerService cmsComponentManagerService;

    /**
     * 添加管理员(包含超级管理员和组件管理员)
     *
     * @param cmsManagerPo
     * @return result
     */
    @PostMapping("/cmsManager")
    public Result addCmsManager(CmsManagerPo cmsManagerPo) {
        BeanValidator.check(cmsManagerPo);
        String componentIds = cmsManagerPo.getComponentIds();
        if (ExcutorConstant.COMPONENT_MANAGER.equals(cmsManagerPo.getManagerFlag()) && StringUtils.isBlank(componentIds)) {
            return ResultUtils.error(400, "您还没有选择组件！");
        }
        try {
            //分配登录账户
            cmsManagerPo.setPassword(CryptographyUtil.md5("123456", "cms"));
            cmsManagerService.save(cmsManagerPo);
            Integer managerId = cmsManagerPo.getId();
            //组件管理员添加关联组件信息
            if (ExcutorConstant.COMPONENT_MANAGER.equals(cmsManagerPo.getManagerFlag())) {
                cmsComponentManagerService.saveComponentIds(componentIds, managerId);
            }
            return ResultUtils.success(ResultEnum.CREATED, null);
        } catch (Exception e) {
            logger.error("新增失败", e);
            return ResultUtils.error(500, "新增失败");
        }
    }

    /**
     * 删除CmsManagerPo
     *
     * @param id
     * @return result
     */
    @DeleteMapping("/cmsManager/{id}")
    public Result deleteCmsManagerPo(@PathVariable("id") Integer id) {
        CmsManagerPo cmsManagerPo = new CmsManagerPo();
        cmsManagerPo.setId(id);
        cmsManagerPo = cmsManagerService.get(cmsManagerPo);
        if (null != cmsManagerPo) {
            cmsManagerService.deleteManager(cmsManagerPo);
        }
        return ResultUtils.success(ResultEnum.DELETED, null);
    }

    /**
     * 修改管理员
     *
     * @param cmsManagerPo
     * @return
     */
    @PutMapping("/cmsManager")
    public Result editCmsManager(CmsManagerPo cmsManagerPo) {
        BeanValidator.check(cmsManagerPo);
        if (null == cmsManagerPo.getId()) {
            return ResultUtils.error(400, "数据请求错误");
        }
        String componentIds = cmsManagerPo.getComponentIds();
        if (ExcutorConstant.COMPONENT_MANAGER.equals(cmsManagerPo.getManagerFlag()) && StringUtils.isBlank(componentIds)) {
            return ResultUtils.error(400, "您还没有选择组件！");
        }
        try {
            Integer managerId = cmsManagerPo.getId();
       /*     deleteCmsManagerPo(managerId);
            //分配登录账户
            cmsManagerPo.setPassword(CryptographyUtil.md5("123456", "cms"));*/
            cmsManagerService.update(cmsManagerPo);
            CmsComponentManagerPo cmsComponentManagerPo = new CmsComponentManagerPo();
            cmsComponentManagerPo.setManagerId(managerId);
            cmsComponentManagerService.delete(cmsComponentManagerPo);
            //组件管理员添加关联组件信息
            if (ExcutorConstant.COMPONENT_MANAGER.equals(cmsManagerPo.getManagerFlag())) {
                cmsComponentManagerService.saveComponentIds(componentIds, managerId);
            }
            return ResultUtils.success(ResultEnum.CREATED, null);
        } catch (Exception e) {
            logger.error("修改失败", e);
            return ResultUtils.error(500, "修改失败");
        }
    }

    /**
     * 查看个人信息详情
     *
     * @param id
     * @return result
     */
    @GetMapping("/cmsManager/{id}")
    public Result getManagerInfo(@PathVariable("id") Integer id) {
        CmsManagerPo cmsManagerPo = new CmsManagerPo();
        cmsManagerPo.setId(id);
        ManagerInfoVo managerInfo = cmsManagerService.getManagerInfo(cmsManagerPo);
        return ResultUtils.success(managerInfo);
    }

    /**
     * 查询CmsManagerPo列表
     *
     * @param cmsManagerPo
     * @return result
     */
    @GetMapping("/cmsManagers")
    public Result listAll(CmsManagerPo cmsManagerPo) {
        List<CmsManagerPo> list = cmsManagerService.listAll(cmsManagerPo);
        return ResultUtils.success(list);
    }

    /**
     * 分页查询组件管理员信息（包含关联组件）
     *
     * @param cmsManagerPo
     * @param pageIndex
     * @param pageSize
     * @return result
     */
    @GetMapping("/cmsManagers/page")
    public Result listPage(CmsManagerPo cmsManagerPo, @RequestParam(value = "pageIndex",
            required = false, defaultValue = "1")
            Integer pageIndex, @RequestParam(value = "pageSize", required = false, defaultValue =
            "10") Integer pageSize) {
        //根据组件名
        if (StringUtils.isNotEmpty(cmsManagerPo.getComponentNames())) {
            cmsManagerPo.setComponentNames("%".concat(cmsManagerPo.getComponentNames())
                    .concat("%"));
        } else {
            cmsManagerPo.setComponentNames(null);
        }
        QueryResult<CmsManagerPo> result = cmsManagerService.selectManagerInfos(cmsManagerPo, pageIndex, pageSize);
        long total = result.getTotalrecord();
        Map<String, Object> map = new HashMap(16);
        if (total > 0) {
            map.put("totalRecord", total);
            map.put("resultList", result.getResultlist());
        }
        return ResultUtils.success(map);
    }


    /**
     * 修改密码
     */
    @ApiOperation(value = "修改密码", httpMethod = "PUT")
    @PutMapping("/setPass")
    public Result changePass(@RequestParam("id") Integer id,
                             @RequestParam("oldPass") String oldPass, @RequestParam String newPass) {
        if (newPass.equals(oldPass)) {
            return ResultUtils.error(400, "新旧密码相同！");
        }
        CmsManagerPo cmsManagerPo = new CmsManagerPo();
        cmsManagerPo.setId(id);
        cmsManagerPo.setPassword(CryptographyUtil.md5(oldPass, "cms"));
        cmsManagerPo = cmsManagerService.get(cmsManagerPo);
        if (null == cmsManagerPo) {
            return ResultUtils.error(400, "当前密码输入错误！");
        }
        try {
            cmsManagerPo.setPassword(CryptographyUtil.md5(newPass, "cms"));
            cmsManagerService.update(cmsManagerPo);
            return ResultUtils.success(ResultEnum.CREATED, null);
        } catch (Exception e) {
            logger.error("修改失败!", e);
            throw new ServiceException(400, "修改!");
        }

    }
}

